package com.jvup.common.dal.base;

import com.lzy.okgo.model.HttpParams;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Signer {

    private static final String SIGN_KEY = "key=!ZXFVFiifa%fadfasdfKVAD!";

    public static void sign(HttpParams params) {
        params.put("timeStamp", "" + (System.currentTimeMillis() / 1000L));
        StringBuilder sb = new StringBuilder();
        Map<String, String> map = new HashMap<>();
        for(Map.Entry<String, List<String>> entry : params.urlParamsMap.entrySet()){
            map.put(entry.getKey(), entry.getValue().get(0));
        }

        for (Map.Entry<String,String> entry : getSortedMapByKey(map).entrySet()){
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.append(SIGN_KEY);
        String sign = MD5.Md5(sb.toString()).toUpperCase();
        params.put("apiSign", sign);
    }

    private static Map<String , String> getSortedMapByKey(Map<String, String> map){
        Comparator<String> comparator = (o1, o2) -> o1.compareTo(o2);

        Map<String, String> treeMap = new TreeMap<>(comparator);
        for (Map.Entry<String, String> entry : map.entrySet()){
            treeMap.put(entry.getKey(), entry.getValue());
        }

        return treeMap;
    }

}
